package DMSXL._2023Before.ListNode_;

/*public class removeNthFromEnd_ {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);
        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        Solution solution = new Solution();
        head = solution.removeNthFromEnd(head,2);

        while(head != null){
            System.out.println(head.val);
            head = head.next;
        }
    }
}
/*class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode curhead = new ListNode();
        curhead.next = head;
        ListNode temp = curhead;

        ListNode[] pres = new ListNode[30];
        int count = 0;
        while(temp.next != null){
            pres[count] = temp.next;
            count++;
            temp = temp.next;
        }
        System.out.println(count);
        if(count == n){
            curhead.next = curhead.next.next;
        }else {
            pres[count - n - 1 ].next = pres[count - n].next;
        }
        return curhead.next;

    }
}

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyNode = new ListNode(0);
        dummyNode.next = head;

        ListNode fastIndex = dummyNode;
        ListNode slowIndex = dummyNode;

        // 只要快慢指针相差 n 个结点即可
        for (int i = 0; i <= n  ; i++){
            fastIndex = fastIndex.next;
        }

        while (fastIndex.next != null){
            fastIndex = fastIndex.next;
            slowIndex = slowIndex.next;
        }

        //此时 slowIndex 的位置就是待删除元素的前一个位置。
        //具体情况可自己画一个链表长度为 3 的图来模拟代码来理解
        slowIndex.next = slowIndex.next.next;
        return dummyNode.next;

    }
}*/